<template>
  <div class="box">
    <el-form
      ref="ruleFormRef"
      :model="projectForm"
      label-position="top"
      class="demo-form-inline"
      label-width="120px"
      :inline="true"
      :rules="rules"
    >
      <el-form-item :label="projectCategory == 2 ? '项目类型-大类' : '项目级别'" prop="level">
        <el-select
          :disabled="!title.includes('新增')"
          v-model="projectForm.level"
          @change="changeLevel"
          placeholder="请选择项目级别"
        >
          <el-option
            v-for="item in store.state.projectCenter.projectDict.XMZX_LEVEL_TYPE"
            :key="item.itemValue"
            :label="item.itemText"
            :value="item.itemValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="page-list" label="项目名称:" required prop="projectName">
        <el-input v-model="projectForm.projectName" disabled placeholder="请选择中咨项目" />
        <el-button
          :disabled="!title.includes('新增')"
          class="choose-btn"
          @click="handleProject"
          type="primary"
          >选择项目</el-button
        >
      </el-form-item>
      <el-form-item label="主数据编号:" v-if="projectCategory == 2">
        <el-input v-model="projectForm.primaryDataNumber" disabled placeholder="项目关联带入" />
      </el-form-item>
      <el-form-item label="项目编号:">
        <el-input v-model="projectForm.projectNumber" disabled placeholder="项目关联带入" />
      </el-form-item>
      <el-form-item class="page-list" label="主项目:" prop="mainProjectId">
        <el-input v-model="projectForm.mainProjectName" disabled placeholder="请选择主项目" />
        <el-button
          :disabled="title.includes('详情')"
          class="choose-btn"
          @click="handleMainProject"
          type="primary"
          >选择项目</el-button
        >
      </el-form-item>
      <el-form-item label="项目外文名称:">
        <el-input v-model="projectForm.foreignName" maxlength="100" placeholder="项目关联带入" />
      </el-form-item>
      <el-form-item label="立项年份:" prop="projectYear">
        <el-input
          :disabled="title.includes('详情')"
          v-model="projectForm.projectYear"
          maxlength="4"
          @input="projectForm.projectYear = projectForm.projectYear.replace(/^(0+)|[^\d]+/g, '')"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="关联部门:">
        <!-- <popup-tree-input
          :disabled="title.includes('详情')"
          :props="data.deptTreeProps"
          :data="orgList"
          :prop="projectForm.departmentName"
          :current-change-handle="handleDepartment"
        /> -->
        <el-input
          :disabled="title.includes('详情')"
          maxlength="200"
          v-model="projectForm.departmentName"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="项目曾用名:">
        <el-input
          :disabled="title.includes('详情')"
          maxlength="100"
          v-model="projectForm.formerName"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="项目类型:" prop="projectType">
        <el-select
          :disabled="title.includes('详情')"
          @change="changeProjectType"
          v-model="projectForm.projectType"
          placeholder="请选择"
          no-data-text="请先选择项目级别"
        >
          <el-option
            v-for="item in (data.typeList as any)"
            :key="item.itemValue"
            :label="item.itemText"
            :value="item.itemValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="项目来源:" prop="projectSource">
        <el-select
          :disabled="title.includes('详情')"
          v-model="projectForm.projectSource"
          placeholder="请选择"
        >
          <el-option
            v-for="item in store.state.projectCenter.projectDict.KHGL_XMZL_SOURCE"
            :key="item.itemValue"
            :label="item.itemText"
            :value="item.itemValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="专业类型（一级）:" prop="primaryProfessionType">
        <el-select
          :disabled="title.includes('详情')"
          @change="handlePrimaryProfession"
          v-model="projectForm.primaryProfessionType"
          placeholder="请选择"
        >
          <el-option
            v-for="item in store.state.projectCenter.projectDict.XMZX_PROFESSIONAL_TYPE"
            :key="item.itemValue"
            :label="item.itemText"
            :value="item.itemValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="专业类型（二级）:" prop="secondaryProfessionType">
        <el-select
          :disabled="title.includes('详情')"
          @change="handleSecondaryProfession"
          v-model="projectForm.secondaryProfessionType"
          no-data-text="请先选择专业类型（一级）"
          placeholder="请选择"
        >
          <el-option
            v-for="item in (data.secondaryProfessionList as any)"
            :key="item.itemValue"
            :label="item.itemText"
            :value="item.itemValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="专业类型（三级）:" prop="tertiaryProfessionType">
        <el-select
          :disabled="title.includes('详情')"
          v-model="projectForm.tertiaryProfessionType"
          no-data-text="请先选择专业类型（二级）"
          placeholder="请选择"
        >
          <el-option
            v-for="item in (data.tertiaryProfessionList as any)"
            :key="item.itemValue"
            :label="item.itemText"
            :value="item.itemValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="委托单位:">
        <!-- <popup-tree-input
          :disabled="title.includes('详情')"
          :props="data.deptTreeProps"
          :data="orgList"
          :prop="projectForm.entrustedUnitName"
          :current-change-handle="handleEntrustedUnit"
        /> -->
        <el-input
          :disabled="title.includes('详情')"
          maxlength="100"
          v-model="projectForm.entrustedUnitName"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="内部承担单位:">
        <popup-tree-input
          :disabled="title.includes('详情')"
          :props="data.deptTreeProps"
          :data="orgList"
          :prop="projectForm.internalUnitName"
          :current-change-handle="handleInternalUnit"
        />
      </el-form-item>
      <el-form-item label="外部承担单位:" v-if="projectCategory == 2" class="page-list">
        <!-- <popup-tree-input
          :props="data.deptTreeProps"
          :data="allOrgList"
          :prop="projectForm.undertakingUnitName"
          :current-change-handle="handleUndertakingUnit"
        /> -->
        <el-input
          :disabled="title.includes('详情')"
          v-model="projectForm.undertakingUnitName"
          maxlength="30"
          show-word-limit
          placeholder="项目关联带入"
        />
      </el-form-item>
      <el-form-item label="项目负责人:">
        <user-list-modal
          :disabled="title.includes('详情')"
          v-model="projectForm.projectLeaderName"
          @update:modelValue="handleProjectLeader"
          :default-users="[]"
          :multiple="false"
          :devType="'platform'"
        />
      </el-form-item>
      <el-form-item label="联系电话:" prop="contactNumber">
        <el-input
          :disabled="title.includes('详情')"
          v-model="projectForm.contactNumber"
          maxlength="11"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="项目开始时间:">
        <el-date-picker
          :disabled="title.includes('详情')"
          v-model="projectForm.startTime"
          value-format="YYYY-MM-DD"
          type="date"
          :disabled-date="disabledStartDate"
          placeholder="请选择"
          clearable
        />
      </el-form-item>
      <el-form-item label="项目结束时间:">
        <el-date-picker
          :disabled="title.includes('详情')"
          v-model="projectForm.endTime"
          value-format="YYYY-MM-DD"
          type="date"
          :disabled-date="disabledEndDate"
          placeholder="请选择"
          clearable
        />
      </el-form-item>
      <el-form-item label="总经费(万元):">
        <el-input
          :disabled="title.includes('详情')"
          v-model="projectForm.totalFunding"
          type="text"
          @input="projectForm.totalFunding = NumberCheck(projectForm.totalFunding)"
          :maxlength="10"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="项目总费用币种:">
        <el-select
          :disabled="title.includes('详情')"
          filterable
          v-model="projectForm.fundingCurrency"
          placeholder="请选择"
          @change="changeFundingCurrency"
        >
          <el-option
            v-for="item in store.state.projectCenter.projectDict.XMZX_FUNDING_CURRENCY"
            :key="item.itemValue"
            :label="item.itemText"
            :value="item.itemValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属单位:">
        <popup-tree-input
          :disabled="title.includes('详情')"
          :props="data.deptTreeProps"
          :data="orgList"
          :prop="projectForm.affiliatedUnitName"
          :current-change-handle="handleAffiliatedUnit"
        />
      </el-form-item>
      <el-form-item label="所属二级单位:">
        <popup-tree-input
          :disabled="title.includes('详情')"
          :props="data.deptTreeProps"
          :data="orgList"
          :prop="projectForm.secondaryUnitName"
          :current-change-handle="handleSecondaryUnit"
        />
      </el-form-item>
      <el-form-item label="工程领域:">
        <el-select
          :disabled="title.includes('详情')"
          v-model="projectForm.engineeringField"
          placeholder="请选择"
          @change="changeEngineeringField"
        >
          <el-option
            v-for="item in store.state.projectCenter.projectDict.XMZX_ENGINEERING_FIELD"
            :key="item.itemValue"
            :label="item.itemText"
            :value="item.itemValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="研究类别:">
        <el-select
          :disabled="title.includes('详情')"
          v-model="projectForm.researchCategory"
          placeholder="请选择"
        >
          <el-option
            v-for="item in store.state.projectCenter.projectDict.XMZX_STUDY_TYPE"
            :key="item.itemValue"
            :label="item.itemText"
            :value="item.itemValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="研究方向:">
        <el-select
          :disabled="title.includes('详情')"
          v-model="projectForm.researchDirection"
          placeholder="请选择"
        >
          <el-option
            v-for="item in store.state.projectCenter.projectDict.XMZX_STUDY_DIRECTION"
            :key="item.itemValue"
            :label="item.itemText"
            :value="item.itemValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产业链:">
        <el-select
          :disabled="title.includes('详情')"
          v-model="projectForm.industrialChain"
          placeholder="请选择"
        >
          <el-option
            v-for="item in store.state.projectCenter.projectDict.XMZX_INDUSTRY_CHAIN"
            :key="item.itemValue"
            :label="item.itemText"
            :value="item.itemValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="title?.indexOf('工程应用') != -1"
        label="专利权属声明:"
        prop="patentOwnershipDeclaration"
      >
        <el-input
          :disabled="title.includes('详情')"
          maxlength="20"
          v-model="projectForm.patentOwnershipDeclaration"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item
        v-if="title?.indexOf('工程应用') != -1"
        label="软著信息:"
        prop="softwareCopyright"
      >
        <el-input
          :disabled="title.includes('详情')"
          maxlength="20"
          v-model="projectForm.softwareCopyright"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="备注:" style="width: 100%">
        <el-input
          :disabled="title.includes('详情')"
          v-model="projectForm.remark1"
          :rows="2"
          maxlength="100"
          show-word-limit
          type="textarea"
          placeholder="请选择"
        />
      </el-form-item>
      <el-form-item label="研发目标:" style="width: 100%">
        <el-input
          :disabled="title.includes('详情')"
          v-model="projectForm.researchTarget"
          :rows="5"
          type="textarea"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="主要研究内容:" style="width: 100%">
        <el-input
          :disabled="title.includes('详情')"
          v-model="projectForm.mainResearchContent"
          :rows="5"
          type="textarea"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="立项申请书：" style="width: 100%">
        <div style="display: flex; flex-direction: column">
          <el-upload
            :disabled="title.includes('详情')"
            v-model:file-list="data.projectApplication"
            ref="uploadRef"
            :limit="5"
            :headers="headers"
            action="/fastDfs/file/upload"
            :on-success="handleApplication"
            :on-preview="previewApplication"
            :on-remove="removeApplication"
            :on-exceed="handleExceedApplication"
            :on-error="handleError"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="RD表" style="width: 100%">
        <el-upload
          :disabled="title.includes('详情')"
          v-model:file-list="data.rdForm"
          ref="uploadRef"
          :limit="5"
          :headers="headers"
          action="/fastDfs/file/upload"
          :on-success="handleRdForm"
          :on-preview="previewRdForm"
          :on-remove="removeRdForm"
          :on-exceed="handleExceed"
          :on-error="handleError"
        >
          <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item
        v-if="title?.indexOf('工程应用') != -1"
        label="专利权属声明附件"
        style="width: 100%"
      >
        <el-upload
          :disabled="title.includes('详情')"
          v-model:file-list="data.patentDeclarationAttachment"
          ref="uploadRef"
          :limit="5"
          :headers="headers"
          action="/fastDfs/file/upload"
          :on-success="handleDeclaration"
          :on-preview="previewDeclaration"
          :on-remove="removeDeclaration"
          :on-exceed="handleExceed"
          :on-error="handleError"
        >
          <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item v-if="title?.indexOf('工程应用') != -1" label="软著录屏" style="width: 100%">
        <el-upload
          :disabled="title.includes('详情')"
          v-model:file-list="data.softwareScreenshot"
          ref="uploadRef"
          :limit="5"
          :headers="headers"
          action="/fastDfs/file/upload"
          :on-success="handleSoftware"
          :on-preview="previewSoftware"
          :on-remove="removeSoftware"
          :on-exceed="handleExceed"
          :on-error="handleError"
        >
          <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item v-if="title?.indexOf('工程应用') != -1" label="论文" style="width: 100%">
        <el-upload
          :disabled="title.includes('详情')"
          v-model:file-list="data.paper"
          ref="uploadRef"
          :limit="5"
          :headers="headers"
          action="/fastDfs/file/upload"
          :on-success="handlePaper"
          :on-preview="previewPaper"
          :on-remove="removePaper"
          :on-exceed="handleExceed"
          :on-error="handleError"
        >
          <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item v-if="title?.indexOf('工程应用') != -1" label="标准" style="width: 100%">
        <el-upload
          :disabled="title.includes('详情')"
          v-model:file-list="data.constructionMethod"
          ref="uploadRef"
          :limit="5"
          :headers="headers"
          action="/fastDfs/file/upload"
          :on-success="handleStandard"
          :on-preview="previewStandard"
          :on-remove="removeStandard"
          :on-exceed="handleExceed"
          :on-error="handleError"
        >
          <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item v-if="title?.indexOf('工程应用') != -1" label="工法" style="width: 100%">
        <el-upload
          :disabled="title.includes('详情')"
          v-model:file-list="data.constructionMethod"
          ref="uploadRef"
          :limit="5"
          :headers="headers"
          action="/fastDfs/file/upload"
          :on-success="handleConstruction"
          :on-preview="previewConstruction"
          :on-remove="removeConstruction"
          :on-exceed="handleExceed"
          :on-error="handleError"
        >
          <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <ProjectTable
      v-if="data.projectDialog"
      :projectCategory="projectCategory"
      @closeDialog="handleProjectDialog"
      @getProject="getProject"
    ></ProjectTable>
    <el-dialog v-model="data.mainProjectDialog" width="60%" title="选择主项目">
      <MainProjectTable
        v-if="data.mainProjectDialog"
        @getProject="getMainProject"
      ></MainProjectTable>
      <template #footer>
        <el-button @click="data.mainProjectDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import UserListModal from '@/views/project/components/UserListModal/index.vue'
import PopupTreeInput from '@/views/project/components/PopupTreeInput/index.vue'
import { ElMessage } from 'element-plus'
import { defineComponent, reactive, ref, watch, computed } from 'vue'
import { useStore } from 'vuex'
import ProjectTable from './project-table2.vue'
import MainProjectTable from '@/views/project/contract-manage/main-contract/components/project-table.vue'

// import CurrencyTable from '@/views/project/components/CurrencyTable/index.vue'
import { downloadByUrl } from '@/views/science/api/common'
import { type, NumberCheck, ergodicDickName, ergodicTreeName } from '@/utils/utils'
import { getProjectFunds } from '../../api/commom'
import { servicesLoading } from '@/utils/loading'

export default defineComponent({
  components: { ProjectTable, PopupTreeInput, UserListModal, MainProjectTable },
  props: {
    title: {
      type: String,
      default: '',
    },
    projectCategory: {
      type: Number,
    },
  },
  setup(props) {
    const store = useStore()
    const rules = reactive({
      projectName: { required: true, message: '请选择中咨项目' },
      projectYear: { required: true, message: '请选择立项年份' },
      departmentName: { required: true, message: '请选择关联部门' },
      level: { required: true, message: '请选择项目级别' },
      // projectType: { required: true, message: '请选择项目级别' },
      projectType: { required: true, message: '请选择项目类型' },
      projectSource: { required: true, message: '请选择项目来源' },
      primaryProfessionType: { required: true, message: '请选择专业类型（一级）' },
      secondaryProfessionType: { required: true, message: '请选择专业类型（二级）' },
      tertiaryProfessionType: { required: true, message: '请选择专业类型（三级）' },
      entrustedUnit: { required: true, message: '请选择委托单位' },
      internalUnit: { required: true, message: '请选择内部承担单位' },
      projectLeader: { required: true, message: '请选择项目负责人' },
      contactNumber: [
        {
          pattern: /^1[3456789]\d{9}$/,
          message: '请输入正确的手机号',
        },
      ],
      startTime: { required: true, message: '请选择项目开始时间' },
      endTime: { required: true, message: '请选择规定完工日期' },
      totalFunding: { required: true, message: '请输入总经费(万元)' },
      affiliatedUnit: { required: true, message: '请选择所属单位' },
      secondaryUnit: { required: true, message: '请选择所属二级单位' },
      patentOwnershipDeclaration: { required: true, message: '请输入专利权属声明' },
      softwareCopyright: { required: true, message: '请输入软著信息' },
      researchTarget: { required: true, message: '请输入研发目标' },
      mainResearchContent: { required: true, message: '请输入主要研究内容' },
    })
    const data = reactive({
      typeList: [],
      secondaryProfessionList: [],
      tertiaryProfessionList: [],
      projectDialog: false,
      mainProjectDialog: false,
      currencyDialog: false,
      projectList: [] as any, //主项目列表
      deptTreeProps: {
        label: 'name',
        children: 'children',
      },
      projectApplication: [],
      rdForm: [],
      patentDeclarationAttachment: [],
      softwareScreenshot: [],
      paper: [],
      standard: [],
      constructionMethod: [],
    })
    let orgList = JSON.parse(JSON.stringify(store.state.projectCenter.orgList))
    let allOrgList = JSON.parse(JSON.stringify(store.state.projectCenter.allOrgList))

    const ruleFormRef = ref()
    const projectSelect = ref(null)
    //浅克隆项目表单数据
    let projectForm = reactive(store.state.projectCenter.form)
    watch(
      () => store.state.projectCenter.form.projectNumber,
      () => {
        console.log(store.state.projectCenter.form, 'form变化了')
        projectForm = reactive(store.state.projectCenter.form)
      }
    )
    const projectDict = reactive(store.state.projectCenter.projectDict)

    //选择项目负责人的回调
    const handleProjectLeader = (user) => {
      console.log(user, 'handleProjectLeader')
      projectForm.projectLeader = user.userId
      projectForm.projectLeaderName = `${user.cname}`
      projectForm.contactNumber = user.phone
    }
    const changeLevel = (val) => {
      console.log(val, 'changeLevel')
      projectForm.projectName = ''
      projectForm.projectNumber = ''
      projectForm.projectType = ''
      projectForm.projectTypeName = ''
    }
    watch(
      () => projectForm.level,
      () => {
        console.log(projectForm.level, 'form.level变化了')
        store.state.projectCenter.projectDict.XMZX_LEVEL_TYPE?.forEach((obj) => {
          if (obj.itemValue == projectForm.level) {
            data.typeList = obj.children
            console.log(data.typeList, 'data.typeList')
          }
        })
      },
      {
        immediate: true,
      }
    )
    const changeProjectType = (val) => {
      console.log(val, 'changeProjectType')
      ;(data.typeList as any).forEach((obj) => {
        if (obj.itemValue == val) {
          projectForm.projectTypeName = obj.itemText
          console.log(projectForm.projectTypeName)
        }
      })
    }
    const handleProject = () => {
      if (!projectForm.level) {
        ElMessage({
          message: '请选择项目级别',
          type: 'warning',
        })
        return
      }
      data.projectDialog = true
    }
    const handleMainProject = () => {
      // if(!projectForm.projectNumber){
      //   ElMessage({
      //     message: '请先选择中咨项目',
      //     type: 'warning',
      //   })
      //   return
      // }
      data.mainProjectDialog = true
    }
    const handleProjectDialog = (flag) => {
      console.log(flag)
      data.projectDialog = flag
    }
    const getSubjectName = (key) => {
      let name = ''
      switch (key) {
        case 'hj':
          name = '合计'
          break
        case 'gjbk':
          name = '国家拨款'
          break
        case 'gsbk':
          name = '公司拨款'
          break
        case 'cddwbk':
          name = '公司拨款'
          break
        case 'xzdwbk':
          name = '协作单位拨款'
          break
        case 'zc':
          name = '自筹'
          break
        case 'qt':
          name = '其他'
          break
        default:
          break
      }
      return name
    }
    const getProject = (project) => {
      console.log(project, 'getMainproject')
      projectForm.dataid = project.dataid   //项目唯一id
      projectForm.projectName = project.xmmc //项目名称
      projectForm.projectNumber = project.xmbh //项目编号
      projectForm.primaryDataNumber = project.zsjbh //主数据编号
      projectForm.foreignName = project.kyxmwwmc //外文名称
      projectForm.projectYear = project.lxnf //立项年份
      projectForm.department = ergodicTreeName(project.glbm, allOrgList, project.glbm, 'code', 'id') //关联部门
      projectForm.departmentName = project.glbmname //关联部门
      projectForm.formerName = project.xmzym //项目曾用名
      projectForm.level = project.xmlx //项目级别
      // projectForm.levelName = ergodicDickName(project.xmlx, projectDict.XMZX_LEVEL_TYPE) //项目级别名称
      projectForm.projectType = project.xmlx2 //项目类型
      setTimeout(() => {
        projectForm.projectTypeName = ergodicDickName(project.xmlx2, data.typeList) //项目类型名称
      }, 0)
      projectForm.projectSource = project.xmly //项目来源
      // projectForm.projectSourceName = ergodicDickName(project.xmly, projectDict.KHGL_XMZL_SOURCE) //项目来源名称
      projectForm.primaryProfessionType = project.zylx1 //专业类型（一级）
      // projectForm.primaryProfessionTypeName = ergodicDickName(
      //   project.zylx1,
      //   projectDict.XMZX_PROFESSIONAL_TYPE
      // ) //专业类型（一级）名称
      projectForm.secondaryProfessionType = project.zylx2 //专业类型（二级）
      // setTimeout(() => {
      //   projectForm.secondaryProfessionTypeName = ergodicDickName(
      //     project.zylx2,
      //     data.secondaryProfessionList
      //   ) //专业类型（二级）名称
      // }, 0)
      projectForm.tertiaryProfessionType = project.zylx //专业类型（三级）
      // setTimeout(() => {
      //   projectForm.tertiaryProfessionTypeName = ergodicDickName(
      //     project.zylx,
      //     data.tertiaryProfessionList
      //   ) //专业类型（三级）名称
      // }, 0)
      projectForm.entrustedUnit = ergodicTreeName(
        project.wtdw,
        allOrgList,
        project.wtdw,
        'oid',
        'id'
      ) //委托单位
      projectForm.entrustedUnitName = project.wtdwname //委托单位名称
      projectForm.internalUnit = ergodicTreeName(
        project.cddw,
        allOrgList,
        project.cddw,
        'oid',
        'id'
      ) //内部承担单位
      projectForm.internalUnitName = project.cddwname //内部承担单位名称
      projectForm.undertakingUnit = ergodicTreeName(
        project.wbwtdw,
        allOrgList,
        project.wtdw,
        'oid',
        'id'
      ) //外部承担单位
      projectForm.undertakingUnitName = project.wbwtdw_name //外部承担单位名称
      projectForm.projectLeader = project.xmfzr //项目负责人
      projectForm.projectLeaderName = project.xmfzrname //项目负责人名称
      projectForm.contactNumber = project.lxdh //联系电话
      projectForm.startTime = project.xmkssj //项目开始时间
      projectForm.endTime = project.xmjssj //项目结束时间
      projectForm.totalFunding = project.zjf //总经费(万元)
      projectForm.fundingCurrency = project.xmzfybz //项目总费用币种
      projectForm.fundingCurrencyName = ergodicDickName(
        project.xmzfybz,
        projectDict.XMZX_FUNDING_CURRENCY
      ) //项目总费用币种名称
      projectForm.affiliatedUnit = ergodicTreeName(
        project.ssdw,
        allOrgList,
        project.ssdw,
        'oid',
        'id'
      ) //所属单位
      projectForm.affiliatedUnitName = project.ssdwname //所属单位名称
      projectForm.secondaryUnit = ergodicTreeName(
        project.ssejdw,
        allOrgList,
        project.ssejdw,
        'oid',
        'id'
      ) //所属二级单位
      projectForm.secondaryUnitName = project.ssejdwname //所属二级单位名称
      projectForm.engineeringField = project.gcly //工程领域
      projectForm.engineeringFieldName = ergodicDickName(
        project.gcly,
        projectDict.XMZX_ENGINEERING_FIELD
      ) //工程领域名称
      projectForm.researchCategory = project.yjlb //研究类别
      // projectForm.researchCategoryName = ergodicDickName(project.yjlb, projectDict.XMZX_STUDY_TYPE) //研究类别名称
      projectForm.researchDirection = project.yjfx //研究方向
      // projectForm.researchDirectionName = ergodicDickName(
      //   project.yjfx,
      //   projectDict.XMZX_STUDY_DIRECTION
      // ) //研究方向名称
      projectForm.industrialChain = project.cyl //产业链
      // projectForm.industrialChainName = ergodicDickName(
      //   project.cyl,
      //   projectDict.XMZX_INDUSTRY_CHAIN
      // ) //产业链名称
      projectForm.remark1 = project.bz //备注
      projectForm.researchTarget = project.yfmb //研发目标
      projectForm.mainResearchContent = project.zyyjnr //主要研究内容:
      let investObj = project.investment?project.investment[0].input:{}
      delete investObj.hj
      //项目投入列表
      // projectForm.projectInvestmentsList = Object.keys(investObj)
      //   .filter((key) => {
      //     return investObj[key]
      //   })
      //   .map((key) => {
      //     return {
      //       subject: key,
      //       subjectName: getSubjectName(key),
      //       amount: investObj[key],
      //     }
      //   })
      // console.log(investObj, 'project.person')
      // console.log(projectForm.projectInvestmentsList, 'projectForm.projectInvestmentsList')
      //相关人员列表
      projectForm.projectPersonnelsList = project.person.map((item) => {
        return {
          ranking: item.pm,
          personName: item.xm,
          unitName: item.dwqc,
          age: item.nl,
          positionTitle: item.zc,
          workAllocation: item.zmfg,
          projectPosition: item.xmzw,
        }
      })
      // const getSubjectName = (key) => {
      //   let name = ''
      //   switch (key) {
      //     case 'gjbk':
      //       name = '国家拨款'
      //       break
      //     case 'gsbk':
      //       name = '公司拨款'
      //       break
      //     case 'cddwbk':
      //       name = '公司拨款'
      //       break
      //     case 'xzdwbk':
      //       name = '协作单位拨款'
      //       break
      //     case 'zc':
      //       name = '自筹'
      //       break
      //     case 'qt':
      //       name = '其他'
      //       break
      //     default:
      //       break
      //   }
      //   return name
      // }
      //参与单位列表
      projectForm.projectParticipantsList = project.units.map((item) => {
        return {
          ranking: item.pm,
          participationType: item.cylx,
          unitName: item.dwqc,
          workAllocation: item.fg,
          leader: item.fzr,
        }
      })
      const loading = servicesLoading({ fullscreen: true, text: '获取项目经费' })
      //获取项目经费
      getProjectFunds({
        xmType: projectForm.level,
        dataid: projectForm.dataid,
      }).then(res=>{
        loading.close()
        console.log(res.data,'thenProjectFunds');
        projectForm.projectInvestmentsList = res.data.ProjectFunds
        projectForm.ysbys = res.data.ysbys?res.data.ysbys:'0'

      }).catch(res=>{
        loading.close()
        console.log(res.data,'catchProjectFunds');
        projectForm.projectInvestmentsList = res.data.ProjectFunds
        projectForm.ysbys = res.data.ysbys?res.data.ysbys:'0'
      })
      data.projectDialog = false
    }
    const getMainProject = (row) => {
      data.mainProjectDialog = false
      console.log(row, 'row')
      projectForm.mainProjectId = row.id
      projectForm.mainProjectName = row.projectName
    }
    const handlePrimaryProfession = (item) => {
      console.log(item, 'handlePrimaryProfession')
      projectForm.secondaryProfessionType = ''
      projectForm.tertiaryProfessionType = ''
    }
    const handleSecondaryProfession = (item) => {
      // console.log(item, 'handleSecondaryProfession')
      projectForm.tertiaryProfessionType = ''
    }
    watch(
      () => projectForm.primaryProfessionType,
      () => {
        console.log(projectForm.primaryProfessionType, 'form.primaryProfessionType变化了')
        store.state.projectCenter.projectDict.XMZX_PROFESSIONAL_TYPE?.forEach((obj) => {
          if (obj.itemValue == projectForm.primaryProfessionType) {
            data.secondaryProfessionList = obj.children
            console.log(data.secondaryProfessionList, 'data.secondaryProfessionList')
          }
        })
      },
      {
        immediate: true,
      }
    )
    watch(
      () => projectForm.secondaryProfessionType,
      () => {
        // console.log(projectForm.primaryProfessionType, 'form.primaryProfessionType变化了')
        ;(data.secondaryProfessionList as any)?.forEach((obj) => {
          if (obj.itemValue == projectForm.secondaryProfessionType) {
            data.tertiaryProfessionList = obj.children
            console.log(data.tertiaryProfessionList, 'data.tertiaryProfessionList')
          }
        })
      },
      {
        immediate: true,
      }
    )
    const disabledStartDate = (time: Date) => {
      return time.getTime() > new Date(projectForm.endTime).getTime()
    }
    const disabledEndDate = (time: Date) => {
      return time.getTime() < new Date(projectForm.startTime).getTime()
    }
    const handleTertiaryProfession = (item) => {
      console.log(item[0], 'handleTertiaryProfession')
    }
    //关联部门修改
    const handleDepartment = (item) => {
      console.log(item, 'handleDepartment')
      projectForm.department = item.id
      projectForm.departmentName = item.name
    }
    //委托单位修改
    const handleEntrustedUnit = (item) => {
      console.log(item, 'handleEntrustedUnit')
      projectForm.entrustedUnit = item.id
      projectForm.entrustedUnitName = item.name
    }
    //内部承担单位修改
    const handleInternalUnit = (item) => {
      console.log(item, 'handleInternalUnit')
      projectForm.internalUnit = item.id
      projectForm.internalUnitName = item.name
    }
    //外部承担单位修改
    const handleUndertakingUnit = (item) => {
      console.log(item, 'handleUndertakingUnit')
      projectForm.undertakingUnitId = item.id
      projectForm.undertakingUnitName = item.name
    }
    //所属单位修改
    const handleAffiliatedUnit = (item) => {
      console.log(item, 'handleAffiliatedUnit')
      projectForm.affiliatedUnit = item.id
      projectForm.affiliatedUnitName = item.name
    }
    //所属二级单位修改
    const handleSecondaryUnit = (item) => {
      console.log(item, 'handleSecondaryUnit')
      projectForm.secondaryUnit = item.id
      projectForm.secondaryUnitName = item.name
    }
    const changeEngineeringField = (val) => {
      //工程领域名称
      projectForm.engineeringFieldName = ergodicDickName(
        projectForm.engineeringField,
        projectDict.XMZX_ENGINEERING_FIELD
      )
      console.log(projectForm.engineeringFieldName, val, 'changeengineeringField')
    }
    const changeFundingCurrency = (val) => {
      //项目总费用币种名称
      projectForm.fundingCurrencyName = ergodicDickName(
        projectForm.fundingCurrency,
        projectDict.XMZX_FUNDING_CURRENCY
      )
      console.log(projectForm.fundingCurrencyName, val, 'changeFundingCurrency')
    }
    const currencyRef = ref()
    const getCurrency = () => {
      let currencyList = currencyRef.value.hasChoose()
      if (currencyList.length == 1) {
        data.currencyDialog = false
        console.log(currencyList[0], 'currencyList[0]')
        projectForm.fundingCurrency = currencyList[0].zcurrencyCode
        projectForm.fundingCurrencyName = currencyList[0].zcurrencyName
      } else {
        ElMessage({
          message: '请选择一个币种',
          type: 'warning',
        })
      }
    }
    const submitForm = async () => {
      return new Promise((resolve, reject) => {
        ruleFormRef.value.validate((valid) => {
          console.log(valid, 'valid')
          if (valid) {
            resolve('校验成功')
          } else {
            ElMessage({
              message: '请将基本信息补充完整',
              type: 'warning',
            })
            reject('校验失败')
          }
        })
      })
    }
    const handleApplication = (uploadFile) => {
      handleDocument(uploadFile, 'projectApplication')
    }
    const handleRdForm = (uploadFile) => {
      handleDocument(uploadFile, 'rdForm')
    }
    const handleDeclaration = (uploadFile) => {
      handleDocument(uploadFile, 'patentDeclarationAttachment')
    }
    const handleSoftware = (uploadFile) => {
      handleDocument(uploadFile, 'softwareScreenshot')
    }
    const handlePaper = (uploadFile) => {
      handleDocument(uploadFile, 'paper')
    }
    const handleStandard = (uploadFile) => {
      handleDocument(uploadFile, 'standard')
    }
    const handleConstruction = (uploadFile) => {
      handleDocument(uploadFile, 'constructionMethod')
    }
    const handleDocument = (uploadFile, key) => {
      if (uploadFile.code == 200) {
        ElMessage({
          message: '上传成功',
          type: 'success',
        })
        console.log('上传成功uploadFile', uploadFile)
        // let obj = {
        //   fileName:uploadFile.data.fileName,
        //   fileId:uploadFile.data.fileId,
        // }
        let obj = {
          name: uploadFile.data.fileName,
          url: uploadFile.data.path,
        }
        data[key].push(obj)
        console.log(data[key], 'data[key]')
        projectForm[key] = JSON.stringify(data[key])
        console.log(projectForm[key], 'uploadFile.data.path')
      } else {
        ElMessage({
          message: '上传失败',
          type: 'error',
        })
      }
    }
    const handleExceedApplication = () => {
      ElMessage({
        message: '最多上传5个立项申请书',
        type: 'wraning',
      })
    }
    const handleExceed = () => {
      ElMessage({
        message: '最多上传5个附件',
        type: 'wraning',
      })
    }
    const handleError = () => {
      ElMessage({
        message: '上传失败',
        type: 'error',
      })
    }
    const removeApplication = (file, uploadFiles) => {
      handleRemove(file, uploadFiles, 'projectApplication')
    }
    const removeRdForm = (file, uploadFiles) => {
      handleRemove(file, uploadFiles, 'rdForm')
    }
    const removeSoftware = (file, uploadFiles) => {
      handleRemove(file, uploadFiles, 'softwareScreenshot')
    }
    const removeDeclaration = (file, uploadFiles) => {
      handleRemove(file, uploadFiles, 'patentDeclarationAttachment')
    }
    const removePaper = (file, uploadFiles) => {
      handleRemove(file, uploadFiles, 'paper')
    }
    const removeStandard = (file, uploadFiles) => {
      handleRemove(file, uploadFiles, 'standard')
    }
    const removeConstruction = (file, uploadFiles) => {
      handleRemove(file, uploadFiles, 'constructionMethod')
    }
    const handleRemove = (file, uploadFiles, key) => {
      console.log(file, uploadFiles, key, data[key], 'data[key]')
      data[key] = uploadFiles.map((fileItem) => {
        return {
          name: fileItem.name,
          url: fileItem.url,
        }
      })
      projectForm[key] = JSON.stringify(data[key])
    }
    const previewApplication = (file) => {
      preview('projectApplication', file)
    }
    const previewRdForm = (file) => {
      preview('rdForm', file)
    }
    const previewSoftware = (file) => {
      preview('softwareScreenshot', file)
    }
    const previewDeclaration = (file) => {
      preview('patentDeclarationAttachment', file)
    }
    const previewPaper = (file) => {
      preview('paper', file)
    }
    const previewStandard = (file) => {
      preview('standard', file)
    }
    const previewConstruction = (file) => {
      preview('constructionMethod', file)
    }
    const preview = (key, file) => {
      console.log(projectForm[key], key, file)
      window.open(file.url)
    }
    // let applicationFile = computed(() => {
    //   return getFileList('projectApplication')
    // })
    const getFileList = (key) => {
      // console.log(projectForm[key],'projectApplication')
      if (type(projectForm[key])) {
        let fileList = JSON.parse(projectForm[key])
        return fileList
      } else {
        return []
      }
    }
    data.projectApplication = getFileList('projectApplication')
    data.rdForm = getFileList('rdForm')
    data.patentDeclarationAttachment = getFileList('patentDeclarationAttachment')
    data.softwareScreenshot = getFileList('softwareScreenshot')
    data.paper = getFileList('paper')
    data.standard = getFileList('standard')
    data.constructionMethod = getFileList('constructionMethod')
    //附件数据转化
    const getCurrentDayDetailed = computed(() => (item: any) => {
      let str = JSON.parse(item.substring(item.lastIndexOf('|arguments') + 10, item.length))
      console.log([].push(str as never))
      let arr = [].push(str as never)
      // return str
      return arr
    })
    //下载附件
    const downFile = async (row) => {
      await downloadByUrl(row.fileId, row.fileName)
    }

    const cookie = () => localStorage.getItem('token')
    return {
      store,
      downFile,
      ruleFormRef,
      data,
      // applicationFile,
      // rdFormFile,
      // declarationFile,
      // softwareFile,
      // paperFile,
      // standardFile,
      // constructionFile,
      rules,
      projectSelect,
      orgList,
      allOrgList,
      projectForm,
      headers: {
        Authorization: 'Bearer ' + cookie(),
      },
      changeEngineeringField,
      changeFundingCurrency,
      currencyRef,
      getCurrentDayDetailed,
      getCurrency,
      NumberCheck,
      handleProjectDialog,
      handleProject,
      handleMainProject,
      getProject,
      getMainProject,
      handleProjectLeader,
      changeLevel,
      changeProjectType,
      handleDepartment,
      handleEntrustedUnit,
      handleInternalUnit,
      handleUndertakingUnit,
      handlePrimaryProfession,
      handleSecondaryProfession,
      disabledStartDate,
      disabledEndDate,
      handleTertiaryProfession,
      handleAffiliatedUnit,
      handleSecondaryUnit,
      submitForm,
      handleDocument,
      handleExceedApplication,
      handleExceed,
      handleError,
      removeApplication,
      removeRdForm,
      removeSoftware,
      removeDeclaration,
      removePaper,
      removeStandard,
      removeConstruction,
      handleApplication,
      previewApplication,
      handleRdForm,
      previewRdForm,
      handleDeclaration,
      previewDeclaration,
      handleSoftware,
      previewSoftware,
      handlePaper,
      previewPaper,
      handleStandard,
      previewStandard,
      handleConstruction,
      previewConstruction,
    }
  },
  beforeUnmount() {
    console.log('beforeUasdasdnmount')
    for (let key in this.projectForm) {
      this.projectForm[key] = ''
    }
    this.projectForm.projectInvestmentsList = []
    this.projectForm.projectPersonnelsList = []
    this.projectForm.projectParticipantsList = []
    this.projectForm.changeProjectsList = []
  },
})
</script>
<style lang="scss" scoped>
.box {
  max-height: 500px;
  overflow: auto;
}
.demo-form-inline .el-form-item {
  width: 23%;
  // background-color: #512323;
}
.demo-form-inline .page-list {
  width: 47%;
  .choose-btn {
    margin-left: 10px;
  }
}
:deep(.demo-form-inline .el-form-item--small .el-form-item__content) {
  display: flex !important;
}
:deep(.el-cascader--small) {
  width: 100%;
}
/deep/.labelHeight .el-form-item__label {
  line-height: 20px;
}

/deep/.el-date-editor.el-input {
  width: 100%;
}

/deep/.el-date-editor.el-input__inner {
  width: 100%;
}

/deep/.demo-form-inline .el-select {
  width: 100%;
  margin: 0;
}

.el-select {
  width: 100%;
  margin: 0;
}
.el-tag {
  margin-right: 10px;
}
.radio {
  display: flex;
  margin-top: 10px;
}
:deep(.el-form--label-top .el-form-item__label) {
  padding: 0;
}
:deep(.el-upload-list__item.is-success.focusing .el-icon-close-tip) {
  display: none !important;
}
</style>
